<template>
  <div>
    <el-card>
      <div slot="header">
        <div class="flex-x gap-4 pt-2">
          <span>
            <vxe-input v-model="query.keyword" clearable :placeholder="'搜索标题'" size="medium"
              @keyup.enter.native="doSearch"></vxe-input>
          </span>
          <span>
            <vxe-input v-model="query.treeCode" clearable :placeholder="'树编码'" size="medium"
              @keyup.enter.native="doSearch"></vxe-input>
          </span>

          <span>
            <el-button type="primary" plain size="small" @click="doSearch" icon="el-icon-search"
              :loading="loading">搜索</el-button>
          </span>
          <span class="flex-1"></span>
          <span>
            <el-button type="primary" size="small" @click="handleAdd(null)" icon="el-icon-plus">
              添加学校
            </el-button>
          </span>
        </div>
      </div>

      <!-- Section Table -->
      <el-table ref="tableRef" :data="dataList" :loading="loading" stripe size="small" row-key="id" lazy
        :load="loadChildrenOrg" :tree-props="{ children: 'children', hasChildren: 'hasChild' }">
        <el-table-column prop="id" label="ID" width="280"></el-table-column>
        <el-table-column prop="orgName" label="学校名称" align="left"></el-table-column>
        <el-table-column prop="orgType" label="类型" width="100">
          <template slot-scope="scope">
            {{ ORG_TYPE[scope.row.orgType]?.name || '未知' }}
          </template>
        </el-table-column>
        <el-table-column prop="treeCode" label="树编码" ></el-table-column>
        <el-table-column prop="tyOrgId" label="教育云ID" width="260"></el-table-column>
        <el-table-column prop="gmtCreate" label="创建时间" width="150" :visible="false"></el-table-column>
        <el-table-column prop="gmtModified" label="修改时间" width="150"></el-table-column>

        <el-table-column label="操作" width="140" fixed="right">
          <template slot-scope="scope">
            <el-tooltip effect="dark" :content="`添加${getChildOrgTypeName(scope.row)}`" placement="top">
              <el-button plain circle type="success" size="mini" icon="el-icon-plus" @click="handleAdd(scope.row)"
                :disabled="scope.row.orgType >= 7"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="编辑" placement="top">
              <el-button plain circle type="primary" size="mini" icon="el-icon-edit"
                @click="handleEdit(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除" placement="top">
              <el-button plain circle type="danger" size="mini" icon="el-icon-delete"
                @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- Pagination -->
      <div class="flex-x justify-end mt-4 gap-4">
        <el-pagination class="page" @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="query.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="query.limit"
          layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
        <el-button circle size="small" @click="handleTableCustom" icon="el-icon-menu"> </el-button>
      </div>

    </el-card>

    <EditDialog ref="editDialog" @success="handleSaveSuccess" />
  </div>
</template>

<script>
import api from '@/common/api';
import SortOrderEditor from '@/components/admin/SortOrderEditor.vue';
import { DEFAULT_TABLE_CUSTOM_CONFIG, ORG_TYPE } from "@/common/constants";
import EditDialog from './components/EditDialog.vue';


export default {
  name: 'SchoolList',
  components: {
    SortOrderEditor,
    EditDialog
  },
  data() {
    return {
      tableCustomConfig: DEFAULT_TABLE_CUSTOM_CONFIG,
      ORG_TYPE,
      treeConfig: {
        transform: true,
        rowField: 'id',
        parentField: 'parentId',
        lazy: true,
        hasChild: 'hasChild',
        indent: 20,
        loadMethod: this.loadChildrenOrg,
      },
      resolveMap: {},

      // List data
      dataList: [],
      loading: false,
      total: 0,
      query: {
        keyword: '',
        orgType: 2,
        currentPage: 1,
        limit: 10,
      },

    };
  },
  created() {
    this.getDataList();
  },
  methods: {
    async loadChildrenOrg(row, treeNode, resolve) {
      if (!this.resolveMap[row.id]) {
        this.resolveMap[row.id] = { row, treeNode, resolve };
      }
      const { data } = await api.admin_getOrgList({ parentId: row.id });

      resolve(data.data.records.map(item => ({
        ...item,
        hasChild: item.orgType !== 7,
      })));
      if (data.data.records.length === 0) {
        this.$set(this.$refs.tableRef.store.states.lazyTreeNodeMap, row.id, {});
      }
    },
    // Get section list
    async getDataList() {
      try {
        this.loading = true;
        const params = Object.assign({}, this.query);
        const { data } = await api.admin_getOrgList(params);
        this.dataList = data.data.records.map(item => ({
          ...item,
          hasChild: item.orgType !== 7,
          children: []
        }));
        this.total = data.data.total;
      } finally {
        this.loading = false;
      }
    },

    // Filter operations
    doSearch() {
      this.query.currentPage = 1;
      this.getDataList();
    },

    // Handle pagination
    handleSizeChange(val) {
      this.query.limit = val;
      this.getDataList();
    },
    handleCurrentChange(val) {
      this.query.currentPage = val;
      this.getDataList();
    },
    handleTableCustom() {
      this.$refs.table?.openCustom()
    },

    // Handle CRUD operations
    handleAdd(row) {
      if (!row) {
        // 添加学校
        this.$refs.editDialog.open({ orgType: 2 });
      } else {
        // 添加其他节点
        let { orgType = 2 } = row;
        orgType += 1
        if (orgType == 4) {
          orgType = 5;
        }
        this.$refs.editDialog.open({ parentName: row.orgName, orgType, parentId: row.id });
      }

    },
    handleEdit(row) {
      this.$refs.editDialog.open(row);
    },

    getChildOrgTypeName({ orgType }) {
      const value = Number(orgType || 0);
      switch (value) {
        case 2:
          return '校区';
        case 3:
          return '学段';
        case 5:
          return '年级';
        case 6:
          return '班级';
        default:
          return '节点';
      }
    },
    async handleDelete(row) {
      try {
        const typeName = ORG_TYPE[row.orgType]?.name || '节点';
        const confirmResult = await this.$confirm(`确认删除该${typeName}?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          closeOnClickModal: false,
          closeOnPressEscape: false
        });
        if (confirmResult !== 'confirm') {
          return;
        }
        await api.admin_deleteOrg(row.id);
        this.$message.success('删除成功');
        this.handleSaveSuccess(row)
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败');
        }
      }
    },
    async handleStatusChange(row, enabled) {
      const data = { id: row.id, enabled };
      try {
        this.loading = true;
        await api.admin_saveOrg(data);
        this.$message.success(`更新状态成功：已${enabled ? '启用' : '禁用'}`);
        this.getDataList();
      } finally {
        this.loading = false;
      }
    },
    async handleSortUpdate(row, newValue) {
      const data = { id: row.id, sortOrder: newValue };
      try {
        this.loading = true;
        await api.admin_saveOrg(data);
        this.$message.success('更新排序成功');
        this.getDataList();
      } finally {
        this.loading = false;
      }
    },
    handleSaveSuccess(data) {
      if (!data.parentId) {
        this.getDataList()
      } else {
        const { row, treeNode, resolve } = this.resolveMap[data.parentId];
        this.loadChildrenOrg(row, treeNode, resolve);
      }
    },

    // Utils
    formatDate(date) {
      return date;
    },
  }
};
</script>

<style scoped>
.filter-row span {
  margin-right: 20px;
}

.filter-row span button {
  margin-top: 5px;
  margin-bottom: 5px;
}

.filter-row span div {
  margin-top: 8px;
}

.panel-options {
  margin-top: 20px;
  text-align: right;
}

@media screen and (max-width: 768px) {
  .filter-row span {
    margin-right: 5px;
  }

  .filter-row span div {
    width: 80%;
  }
}
</style>
